﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EvinceUI.JQueryDataTable.Model;
using EvincePayroll.Data;
using EvincePayroll.Utility;
using EvinceUI;
using System.Text;
using System.Configuration;

namespace EvinceUI.Controllers
{
    public class AttendanceController : Controller
    {
        //
        // GET: /Attendance/
        [Authorize.SessionExpire]
        public ActionResult AdminAttendanceTable()
        {

            return View();
        }
        public PartialViewResult _AttendanceTable(string fromDate, string toDate)
        {
            ViewBag.FromDate = fromDate;
            ViewBag.ToDate = toDate;

            return PartialView();
        }

        [Authorize.SessionExpire]
        public ActionResult AjaxGetAttendanceAdmin(JQueryDataTableParamModel param, string fromDate,string toDate)
        {
            List<AttendanceData> attendanceList;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
            attendanceList = accountService.GetAttendanceAdmin(employee.Email, Convert.ToDateTime(fromDate), Convert.ToDateTime(toDate));
           if(attendanceList!=null)
           {
               IEnumerable<AttendanceData> filteredRequests;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered

                    var dateFilter = Convert.ToString(Request["sSearch_0"]);
                    var employeeNameFilter = Convert.ToString(Request["sSearch_1"]);
                    var emloyeeIdFilter = Convert.ToString(Request["sSearch_2"]);
                    var statusFilter = Convert.ToString(Request["sSearch_3"]);
                    var arrivalFilter = Convert.ToString(Request["sSearch_4"]);
                    var leavingFilter = Convert.ToString(Request["sSearch_5"]);




                    //Optionally check whether the columns are searchable at all
                    var isDateSearchable = Convert.ToBoolean(Request["bSearchable_0"]);
                    var isEmployeeNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                    var isEmployeeIdSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
                    var isStatusSearchable = Convert.ToBoolean(Request["bSearchable_3"]);
                    var isArrivalSearchable = Convert.ToBoolean(Request["bSearchable_4"]);
                    var isLeavingSearchable = Convert.ToBoolean(Request["bSearchable_5"]);



                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();
                        filter.Append("(").Append(expression.Replace("[FIELD]", "Date.ToUpper()")).Append(") ||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "EmployeeName.ToString().ToUpper()")).Append(")||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "EmployeeId.ToString().ToUpper()")).Append(")");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "Status.ToUpper()")).Append(") ||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "Arrival.ToString().ToUpper()")).Append(")||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "Leaving.ToString().ToUpper()")).Append(")");
                        filteredRequests = attendanceList;
                    }
                    else
                    {

                        filteredRequests = attendanceList
                        .Where(d => isDateSearchable && d.Date.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isEmployeeIdSearchable && d.EmployeeStringId.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isEmployeeNameSearchable && d.EmployeeName.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isStatusSearchable && d.StatusString.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isArrivalSearchable && d.ArrivingTime.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isLeavingSearchable && d.LeavingTime.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        );

                    }
                }
                else
                {
                    filteredRequests = attendanceList;

                }

                var isDate = Convert.ToBoolean(Request["bSortable_0"]);
                var isEmployeeId = Convert.ToBoolean(Request["bSortable_1"]); 
               var isEmployeeName = Convert.ToBoolean(Request["bSortable_2"]);
                var isStatus = Convert.ToBoolean(Request["bSortable_3"]);
                
                var isArriveing = Convert.ToBoolean(Request["bSortable_4"]);
                var isLeaving = Convert.ToBoolean(Request["bSortable_5"]);



                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<AttendanceData, string> orderingFunction = (d => sortColumnIndex == 1 && isDate ? d.Date.ToString() :
                sortColumnIndex == 2 && isEmployeeId ? d.EmployeeStringId.ToString() :
                sortColumnIndex == 3 && isEmployeeName ? d.EmployeeName.ToString() :
                sortColumnIndex == 4 && isStatus ? d.StatusString.ToString() :
                sortColumnIndex == 5 && isArriveing ? d.ArrivingTime.ToString() :
                sortColumnIndex == 6 && isLeaving? d.LeavingTime.ToString() :
                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredRequests = filteredRequests.OrderBy(orderingFunction);
                else
                    filteredRequests = filteredRequests.OrderByDescending(orderingFunction);

                var displayedCompanies = filteredRequests.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var result = from p in displayedCompanies
                             select new[] { 
                            p.Date.ToShortDateString(), 
                             p.EmployeeStringId, 
                             p.EmployeeName, 
                             p.TotalHours,
                             GetAttendanceStatus(p.StatusString), 
                             //p.ArrivingTime.Split('.')[0].ToString(), 
                             //p.LeavingTime.Split('.')[0].ToString()
                             p.ArrivingTime.ToShortTimeString(), 
                             p.LeavingTime.ToShortTimeString(),
                             string.Format("<span style=\"font-size: small; \"><a href=\"#\" onclick=\"GetAttendanceLog('{0}')\">View Details</a></span>", p.AttendanceId)
                             
                             };

                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = attendanceList.Count(),
                    iTotalDisplayRecords = filteredRequests.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
        }
            else
                return Json(new { }, JsonRequestBehavior.AllowGet);
            
        }

        

        public string GetArrivalLeavingTime(string time)
        {
            string splitedTime=string.Empty;
            if(time!=null)
                splitedTime= time.Split('.')[0];
            return splitedTime;
        
        }

        public string GetAttendanceStatus(string status)
        {
            string statusSpan = string.Empty;
            if (status == Constants.LEAVE_REQUEST_UN_APPROVED)
            statusSpan = string.Format("<span style=\"color:Red;\">{0}</span>", status);
            else if(status==Constants.ATTENDANCE_PRESENT)
                statusSpan = string.Format("<span style=\"color:Green;\">{0}</span>", status);
            else if (status == Constants.ATTENDANCE_ABSENT)
                statusSpan = string.Format("<span style=\"color:Red;\">{0}</span>", status);
            else if (status == Constants.ATTENDANCE_APPROVED)
                statusSpan = string.Format("<span style=\"color:Green; font-size: medium; \">{0} Leave</span>", status);
            else if (status == Constants.ATTENDANCE_LEAVE)
                statusSpan = string.Format("<span style=\"color:Green; font-size: medium; \">{0}</span>", status);
            return statusSpan;
        }
        private string GetExpression(string p)
        {
            throw new NotImplementedException();
        }

        public ActionResult MarkAubsent()
        {
            string temp = string.Empty;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
            if (System.DateTime.Now.TimeOfDay.ToString().Split('.')[0] == "20:59:59")
            {
                var result = accountService.MarkAubsent();
            }
            return Json(new { temp}, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        public ActionResult CheckOut(string reason)
        {
            bool result = false;
            if (reason != null)
            {
                Session["CheckIn"] = "0";
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
                result = accountService.CheckOut(employee.Email, reason);
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }
            return View();
        }
        [Authorize]
        public ActionResult CheckIn()
        {
            bool result = false;
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                if (employee != null)
                {
                    Session["CheckIn"] = "1";
                    EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
                    result = accountService.CheckIn(employee.Email);
                    return Json(new { result }, JsonRequestBehavior.AllowGet);
                }
            return View();
        }

        public ActionResult ShowAttendanceDetail(string attendanceId)
        {
            List<AttendanceLogData> AttLogData = null;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService attendanceService = new EvincePayrollService(ServiceTypes.Attendance);
            if (attendanceId != "")
            {

               AttLogData= attendanceService.ShowAttendanceDetail(employee.Email, attendanceId);
            
            }
            return View(AttLogData);
        }

    }
}
